package com.example.wisdomclassroomapi.common.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * JWT 工具类
 */
public class JwtUtil {

    private static final long LIVE_TIME = 1000*60*60*24;        // 24小时

    private static final String KEY = "create by luye";

    /**
     * 生成token
     * @param userId String
     * @return String
     */
    public static String sign(String userId) {
        // 设置过期时间
        Date date = new Date(System.currentTimeMillis() + LIVE_TIME);
        // 私钥和加密算法
        Algorithm algorithm = Algorithm.HMAC256(KEY);
        // 设置头部信息
        Map<String, Object> header = new HashMap<>(2);
        header.put("Type", "Jwt");
        header.put("alg", "HS256");
        // 返回token字符串
        return JWT.create()
                .withHeader(header)
                .withClaim("userId", userId)
                .withExpiresAt(date)
                .sign(algorithm);
    }

    /**
     * 解析token
     * @param token String
     * @return String
     */
    public static String parse(String token) {
        Algorithm algorithm = Algorithm.HMAC256(KEY);
        JWTVerifier verifier = JWT.require(algorithm).build();
        DecodedJWT jwt = verifier.verify(token);
        return jwt.getClaim("userId").asString();
    }
}
